package com.keya.utils;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.druid.DruidConfig;
import com.keya.pull.DatasourceViewVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @author huangshuqiang
 * @version 1.0
 * @description: TODO
 * @date 2022/8/16 17:53
 */
//@Component
@Slf4j
public class DataSourceUtil {
    @Resource
    private DataSource dataSource;
    @Resource
    private DruidDataSourceCreator druidDataSourceCreator;

    public void ensureDataSourceExist(DatasourceViewVO datasourceView) {
        if (((DynamicRoutingDataSource) dataSource).getDataSources().containsKey(datasourceView.getName())) {
            return;
        }
        loadDataSource(datasourceView);
    }

    public void loadDataSource(DatasourceViewVO datasourceView) {
        if (Boolean.TRUE.equals(datasourceView.getEnabled())) {
            return;
        }
        String dsName = datasourceView.getName();
        String url = datasourceView.getUrl();
        String username = datasourceView.getUsername();
        String password = datasourceView.getPassword();
        if (StringUtils.isEmpty(dsName) || StringUtils.isEmpty(url) || StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) || "mysql".equals(dsName)) {
            log.error("DataSource 配置错误");
            return;
        }
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(dsName);
        DruidConfig druidConfig = new DruidConfig();
        druidConfig.setConnectionErrorRetryAttempts(0);
        druidConfig.setBreakAfterAcquireFailure(true);
        druidConfig.setMaxWait(1000);
        DataSource dataSource = druidDataSourceCreator.createDataSource(new DataSourceProperty()
                .setPoolName(dsName)
                .setUrl(url)
                .setUsername(username)
                .setPassword(password)
                .setDruid(druidConfig));
        ds.addDataSource(dsName, dataSource);
    }

    public void removeDataSource(String dsName) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(dsName);
    }
}
